<template>
	<uni-loading v-if="loading"></uni-loading>
	<view class="body" v-else>
		<!--  顶部  -->
		<top-tab :options="stockList" :stockNameProp="stockName" :locationName="locationName" @stockChange="stockChange"
			@handleBarnChoose="handleBarnChoose"></top-tab>

		<view class="top-container no-top" style="height: 130px;">
			<!-- #ifdef APP-PLUS -->
			<!-- <view class="top-container-inner top-container-fiexd" :style="{top: `60px`}"> -->
			<!-- #endif -->
			<!-- #ifndef APP-PLUS -->
			<!-- <view class="top-container-inner top-container-fiexd" :style="{top: `104px`}"> -->
			<!-- #endif -->
			<view class="top-container-inner">
				<uni-list :border="false">
					<uni-list-item :border="false" title="已扫箱数" :rightText="scannedSum ? scannedSum : '0'" />
					<uni-list-item :border="false" title="已扫重量" :rightText="countSum ? countSum : '0'" />
					<uni-list-item :border="false" title="已扫任务数" :rightText="taskSum ? taskSum : '0'" />
				</uni-list>
			</view>
		</view>

		<!--  列表  -->
		<template v-if="dataList && dataList.length > 0">
			<uni-swipe-action>
				<uni-swipe-action-item disabled :left-options="options"
					v-for="(item, index) in dataList" @click="handleDelete(index)">
					<view class="panel" @click="openDetail(item, index)">
						<view class="panel_title" :class="{error: item.error}">
							<view class="panel_title_left">{{ item.taskBillNo }}</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">已扫箱数：</view>
									<view class="panel_content_row_item_value">{{ item.currentCount }}</view>
								</view>
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">已扫重量：</view>
									<view class="panel_content_row_item_value">{{ item.sumCount }}</view>
								</view>
							</view>
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">未扫箱数：</view>
									<view class="panel_content_row_item_value">{{ item.toDoCount }}</view>
								</view>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</template>
		<uni-empty-info v-else label="暂无数据"></uni-empty-info>

		<!--  底部按钮  -->
		<view class="footerPanel">
			<view class="footerPanel_body">
				<button @click="handleReturn" class="footerBtn save">
					<i class="iconfont icon-jinrumore btn_icon trace-back"></i>返回
				</button>
				<button @click="handleConfirm" class="footerBtn scan" type="primary"><i
						class="iconfont icon-cgrk btn_icon"></i>入库
				</button>
			</view>
		</view>

		<!-- 弹出层 -->
		<MaterialPopupThin ref="materialPopupThinRef" title="物料扫描" type="finished" @scanSuccess="handleScanSuccess"
			@success="addUserAllocationBoxList">
		</MaterialPopupThin>

		<BarnPopup ref="barnPopup" @confirm="onLocationChange"></BarnPopup>

		<!-- 详情 -->
		<Detail ref="detailRef" @delete="deleteMaterialBox" hiddenDelete></Detail>
	</view>
</template>
<script>
	import topTab from "@/components/top-tab/top-tab"
	import uniLoading from "../../vBase/components/uni-loading/uni-loading"
	import uniEmptyInfo from "../../vBase/components/uni-empty-info/uni-empty-info"
	import MaterialPopupThin from "@/components/popup/materialPopupThin.vue"
	import BarnPopup from "@/components/popup/barnPopup.vue"
	import Detail from "../pop/detail-material.vue"

	export default {
		components: {
			topTab,
			uniLoading,
			uniEmptyInfo,
			MaterialPopupThin,
			BarnPopup,
			Detail
		},
		data() {
			return {
				loading: false,
				purchaseList: [],
				dataList: [],
				header: {},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#FF4E74'
					}
				}],
				stockList: [],
				stockList: [],
				locationName: '',
				locationNo: '',
				stockNo: '',
				stockName: '',
				scannedSum: 0,
				countSum: 0,
				taskSum: 0,
				detailIndex: null,
			}
		},
		async onLoad(e) {
			if (e.stockName) this.stockName = e.stockName
			if (e.stockNo) this.stockNo = e.stockNo
			if (e.locationNo) this.locationNo = e.locationNo
			if (e.locationName) this.locationName = e.locationName
			await this.getStockList();
			this.initData()
		},
		methods: {
			/** 查询仓库*/
			async getStockList() {
				this.loading = true;
				try {
					let {
						res,
						stockList = []
					} = await this.$api.getCustomerStock();
					if (!res) return;
					this.stockList = stockList;
					if (stockList.length && !this.stockName) this.stockNo = stockList[0].stockNo
				} finally {
					this.loading = false;
				}
			},

			/** 初始化数据 */
			initData() {
				this.getDataList()
			},

			/**
			 * 查看详情
			 */
			async openDetail(material, i) {
				let param = {
					title: '物料明细',
					dataList: material.materialList ?? [],
				}
				this.detailIndex = i
				this.$refs.detailRef.open(param)
			},

			// /**
			//  * 删除箱子
			//  */
			// deleteMaterialBox(e) {
			// 	let {
			// 		material,
			// 		success,
			// 		index
			// 	} = e
			// 	let currentList = JSON.parse(JSON.stringify(this.purchaseList))
			// 	// 如果删除了最后一个箱子,直接删除当前任务
			// 	if (currentList[this.detailIndex].materialList.length === 1) {
			// 		currentList.splice(this.detailIndex, 1);
			// 	} else {
			// 		currentList[this.detailIndex].materialList.splice(index, 1);
			// 	}
			// 	success && success();
			// 	uni.showToast({
			// 		title: "删除成功",
			// 		icon: "none"
			// 	})
			// 	this.saveStorage(currentList)
			// },

			/** 获取数据 */
			async getDataList() {
				this.purchaseList = uni.getStorageSync("to-be-submit-finished") ? JSON.parse(uni.getStorageSync(
					"to-be-submit-finished")) : []
				// 整理相同的任务号在一起 
				this.dataList = this.purchaseList.reduce((pre, cur) => {
					let current = {
						exp: cur.exp,
						produceDate: cur.produceDate,
						billNo: cur.billNo,
						batchNo: cur.batchNo,
						taskBillNo: cur.taskBillNo,
						materialName: cur.materialName,
						materialNo: cur.materialNo,
						materialSpec: cur.materialSpec,
						currentCount: cur.currentCount ?? 0,
						sumCount: cur.sumCount ?? 0,
						unit: cur.unit,
					}
					let index = pre.findIndex(v => v.taskBillNo === cur.taskBillNo)
					if (index > -1) {
						pre[index].materialList.push(current)
					} else {
						pre.push({
							taskBillNo: cur.taskBillNo,
							materialList: [current]
						})
					}
					return pre
				}, [])
				this.handleTotalCalculation()
			},

			// /**
			//  * 添加物料
			//  * @param {Object} e
			//  */
			// async addUserAllocationBoxList(e) {
			// 	try {
			// 		let node = e.reduce((pre, cur) => {
			// 			const curMaterial = {
			// 				boxNo: cur.boxNo,
			// 				batchNo: cur.batchNo,
			// 				comment: cur.comment,
			// 				count: cur.count,
			// 				materialName: cur.materialName,
			// 				materialNo: cur.materialNo,
			// 				materialSpec: cur.materialSpec,
			// 				currentCount: cur.currentCount,
			// 				department: cur.department,
			// 				inStock: cur.inStock,
			// 				insertUserName: cur.insertUserName,
			// 				isDelete: cur.isDelete,
			// 				noPrint: cur.noPrint,
			// 				standard: cur.standard,
			// 				traceBack: cur.traceBack,
			// 				unit: cur.unit,
			// 				unitName: cur.unitName,
			// 			}
			// 			let index = pre.findIndex(v => v.taskBillNo === cur.taskBillNo && v.materialNo === cur
			// 				.materialNo && v.batchNo === cur.batchNo)
			// 			if (index > -1) {
			// 				let materialIndex = pre[index].materialList?.findIndex(v => v.boxNo === cur.boxNo)
			// 				if (materialIndex > -1) {
			// 					uni.showToast({
			// 						title: "请勿重复添加物料",
			// 						icon: "none"
			// 					})
			// 					this.handleMediaPlayer('error')
			// 					this.handleVibrate(2, 500)
			// 					return
			// 				} else {
			// 					pre[index].materialList.push(curMaterial)
			// 				}
			// 			} else {
			// 				pre.push({
			// 					billNo: cur.billNo,
			// 					batchNo: cur.batchNo,
			// 					taskBillNo: cur.taskBillNo,
			// 					materialName: cur.materialName,
			// 					materialNo: cur.materialNo,
			// 					materialSpec: cur.materialSpec,
			// 					currentCount: 1,
			// 					sumCount: curMaterial.count ?? 0,
			// 					materialList: [curMaterial]
			// 				})
			// 			}
			// 			return pre
			// 		}, this.dataList ?? [])
			// 		this.saveStorage(node)
			// 		this.$refs.materialPopupThinRef.close()
			// 		uni.showToast({
			// 			title: "添加成功",
			// 			icon: "none"
			// 		})
			// 		this.handleMediaPlayer('success')
			// 	} finally {}
			// },

			/**
			 * 总数计算
			 */
			handleTotalCalculation() {
				let boxList = []
				this.dataList.forEach(v => {
					if (v.materialList && v.materialList.length) {
						v.currentCount = 0
						v.sumCount = 0
						v.materialList.forEach(m => {
							// 保存所有箱子的重量，和是总重，length是已扫数量
							boxList.push(Number(m.sumCount))
							v.currentCount += Number(m.currentCount)
							v.sumCount += Number(m.sumCount)
						})
					} else {
						v.currentCount = 0
					}
					v.toDoCount = v.currentCount
				})
				this.scannedSum = boxList.length
				this.countSum = boxList.reduce((pre, cur) => pre + Number(cur), 0)
				this.taskSum = this.dataList.length
			},

			/**
			 * 保存列表
			 * @param {Object} list
			 */
			saveStorage(list) {
				this.dataList = JSON.parse(JSON.stringify(list))
				this.handleTotalCalculation()
			},

			/** 提交 */
			handleReturn() {
				uni.navigateBack()
			},

			/**
			 * 选择仓库
			 * @param e
			 */
			stockChange(e) {
				this.stockNo = this.stockList[e].stockNo
				this.initData()
			},

			/**
			 * 选择
			 */
			handleBarnChoose() {
				this.$refs.barnPopup.open(this.stockNo);
			},

			/** 选择仓位*/
			onLocationChange(location) {
				this.locationNo = location.locationNo;
				this.locationName = location.locationName;
			},

			/** 扫码 */
			async handleConfirm() {
				if (!this.stockNo) {
					uni.showToast({
						title: '请选择仓库',
						icon: 'none'
					});
					return;
				}
				if (!this.locationNo) {
					uni.showToast({
						title: '请选择仓位',
						icon: 'none'
					});
					return;
				}
				if (!this.dataList || !this.dataList.length) {
					uni.showToast({
						title: '请重新添加信息',
						icon: 'none'
					});
					return;
				}
			
					const self = this
					uni.showModal({
						title: '提示',
						content: '是否确认入库？',
						success(res) {
							if (res.confirm) {
								try {
									// 展开列表
									let boxListParam = self.purchaseList.reduce((pre, cur) => {
										let node = JSON.parse(JSON.stringify(cur))
										delete node.boxList
										if (cur.boxList && cur.boxList.length) {
											cur.boxList.forEach(v => {
												pre.push(JSON.parse(JSON.stringify(Object.assign(node, v))))
											})
										}
										return pre
									}, [])
									self.$api["createSimplePrdIn"]({
										stockNo: self.stockNo,
										locationNo: self.locationNo,
										boxList: boxListParam
									}).then(res => {
										if (res.res){
											uni.showToast({
												title: '入库成功',
												icon: 'none'
											});
											// uni.removeStorageSync("to-be-submit-finished")
											// uni.navigateBack({
											// 	delta: 2
											// })	
										
										}
									})
								} catch(e){
									
								} finally{
									setTimeout(() =>{
										uni.removeStorageSync("to-be-submit-finished")
										uni.navigateBack({
											delta: 2
										})	
									},20000)
								}
							}
						}
					})
					
			
			},

			// /**
			//  * 扫码成功
			//  */
			// async handleScanSuccess(e) {
			// 	try {
			// 		let res = await this.$api.getTaskMaterialByBox({
			// 			boxNo: typeof e === 'string' ? [e] : e,
			// 		})
			// 		if (!res.res) return
			// 		// 直接关闭面板
			// 		this.materialList = res.hasOwnProperty('data') ? res.data : [res] ?? []
			// 		if (this.materialList && this.materialList.length) {
			// 			this.addUserAllocationBoxList(this.materialList)
			// 		}
			// 	} catch (e) {
			// 		// 震动两次、错误提示音
			// 		this.handleVibrate(2, 500)
			// 		this.handleMediaPlayer('error')
			// 	}
			// },

			/**
			 * 删除物料
			 * @param {Object} i
			 */
			handleDelete(i) {
				const self = this
				uni.showModal({
					title: '提示',
					content: '是否删除物料？',
					success(res) {
						if (res.confirm) {
							self.purchaseList.splice(i, 1)
							self.saveStorage(self.dataList ?? [])
							uni.showToast({
								title: '删除成功',
								icon: 'none'
							})
						}
					}
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import "../../static/css/common";

	.error {
		color: red;
	}

	.save {
		width: 140px !important;
	}

	.trace-back {
		transform: rotate(180deg);
	}
</style>
